package com.suishoupai.xmb.service;

import com.suishoupai.xmb.dao.CutEvaluateMapper;
import com.suishoupai.xmb.dao.CutOrdersMapper;
import com.suishoupai.xmb.dao.CutUserSaleMapper;
import com.suishoupai.xmb.dao.EvaluateMapper;
import com.suishoupai.xmb.entity.CutEvaluate;
import com.suishoupai.xmb.entity.Evaluate;
import com.suishoupai.xmb.entity.Orders;
import com.suishoupai.xmb.exception.XmbException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by caojian on 2017/4/13.
 */
@Service
public class EvaluateService {
    @Autowired
    private EvaluateMapper evaluateMapper;
    @Autowired
    private CutEvaluateMapper cutEvaluateMapper;
    @Autowired
    private CutOrdersMapper cutOrdersMapper;
    @Autowired
    private CutUserSaleMapper cutUserSaleMapper;

    /**
     * 添加评价
     *
     * @param evaluate
     * @throws XmbException
     */
    @Transactional
    public void add(Evaluate evaluate) throws XmbException {
        Orders orders = cutOrdersMapper.selectByPrimaryKey(evaluate.getOrdersId());
        long userId = evaluate.getUserId();
        if (orders.getUserId() != userId) {
            throw XmbException.newError("非法请求！");
        }
        evaluate.setSaleId(orders.getSaleId());
        evaluate.setCreateTime(System.currentTimeMillis());
        if (cutEvaluateMapper.selectByOrderId(evaluate.getOrdersId()) != null) {
            throw XmbException.newRepeatRequest();
        }
        if (evaluateMapper.insertSelective(evaluate) == 0) {
            throw new RuntimeException("插入失败");
        }
        if (cutUserSaleMapper.addScore(orders.getSaleId(), evaluate.getScore()) == 0) {
            throw new RuntimeException("更新失败");
        }
    }

    /**
     * 获取店铺的评价列表
     *
     * @param saleId
     * @return
     */
    public List<CutEvaluate> getEvaluateListBySaleId(long saleId) {
        return cutEvaluateMapper.selectCutListBySaleId(saleId);
    }

    /**
     * 获取店铺的评价列表
     *
     * @param saleId
     * @param evaluateId 用于分页(移动端使用)
     * @return
     */
    public List<CutEvaluate> getEvaluateListBySaleId(long saleId, Long evaluateId) {
        return cutEvaluateMapper.selectCutListBySaleIdWx(saleId, evaluateId);
    }

    /**
     * 回复
     */
    public void reply(long evaluateId, long saleId, String reply) throws XmbException {
        Evaluate evaluate = cutEvaluateMapper.selectByPrimaryKey(evaluateId);
        if (saleId != evaluate.getSaleId()) {
            throw XmbException.newError("非法操作！");
        }
        Evaluate updateEvaluate = new Evaluate();
        updateEvaluate.setId(evaluateId);
        updateEvaluate.setReply(reply);
        if (cutEvaluateMapper.updateByPrimaryKey(updateEvaluate) == 0) {
            throw new RuntimeException("更新失败！");
        }
    }
}

